package com.hb.software.controller.department;

import com.hb.software.controller.BaseController;
import com.hb.software.department.DepartmentService;
import com.hb.software.domain.Result;
import com.hb.software.entity.department.Department;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("department")
public class DepartmentController extends BaseController<Department,Long,DepartmentService> {

    private static final Logger logger = LogManager.getLogger(DepartmentController.class.getName());

    private DepartmentService departmentService;

    @Autowired
    public void setDepartmentService(DepartmentService departmentService) {
        this.departmentService = departmentService;
        this.manager = this.departmentService;
    }

    @PostMapping("/findAllDepartment")
    public List findAllDepartment(){
        List list = this.manager.findAll();
        return list;
    }
    @PostMapping("/save")
    public Result save(@RequestBody Department department){
        List<Department> list = this.manager.findAll();
        for(int i =0;i<list.size();i++){
            if(department.getName().equals(list.get(i).getName())){
                return Result.error("该部门已存在!");
            }
        }
        try {
            department.setId(this.manager.findLastId()+1);
        }catch (Exception e) {
            department.setId(1L);
        }
        this.manager.save(department);
        return Result.success();
    }

    @PostMapping("/findByName")
    public Result findByName(@RequestBody String name) throws UnsupportedEncodingException {
        //处理中文乱码问题
        name = URLDecoder.decode(name,"UTF-8");
        name = name.substring(0,name.length()-1);
        logger.info(name);
        List list=departmentService.findByName(name);
        return Result.success(list);
    }

    @PostMapping("/findLastId")
    public Result findLastId()   {
        long id = departmentService.findLastId();
        return Result.success(id);
    }
}
